{% extends "base.html" %}

{% block title %}设备入库{% endblock %}

{% block content %}
<div class="container-xl py-4">
    <h2 class="page-title">设备入库</h2>
    <div class="row mb-4">
        <div class="col">
            <a href="{{ url_for('dashboard') }}" class="btn btn-outline-primary">
                <i class="fas fa-arrow-left"></i> 返回
            </a>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0"><i class="fas fa-box-open me-2"></i>设备入库</h4>
        </div>
        <div class="card-body">
            <form id="inboundForm" method="POST" enctype="multipart/form-data">
                <!-- 时间模块 -->
                <div class="card mb-4 border-primary">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-clock me-2"></i>时间</h5>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="date" class="form-label">入库时间</label>
                            <input type="datetime-local" class="form-control" id="date" name="date" required>
                        </div>
                    </div>
                </div>

                <!-- SN码识别模块 -->
                <div class="card mb-4 border-primary">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-barcode me-2"></i>SN码识别</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="sn_image" class="form-label">上传SN码图片</label>
                                    <div class="input-group">
                                        <input type="file" class="form-control" id="sn_image" name="sn_image" accept="image/*" required>
                                    </div>
                                    <small class="form-text text-muted">支持PNG、JPG、JPEG、BMP格式的图片</small>
                                </div>
                                <div class="form-group mb-3">
                                    <button type="button" class="btn btn-primary" id="recognize-btn">
                                        <i class="fas fa-barcode me-2"></i>识别SN码
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="sn" class="form-label">SN码</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="sn" name="sn" required>
                                        <button type="button" class="btn btn-outline-secondary" id="clearSn">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                    <small class="form-text text-muted">支持手动输入或扫描识别</small>
                                </div>
                                <!-- 批量导入SN码 -->
                                <div class="form-group mb-3">
                                    <label class="form-label">批量导入SN码（.txt，每行一个）</label>
                                    <div class="input-group mb-2">
                                        <input type="file" class="form-control" id="sn_txt_file" accept=".txt">
                                        <button type="button" class="btn btn-outline-primary" id="importSnTxt">导入</button>
                                    </div>
                                    <textarea class="form-control" id="snListArea" rows="4" readonly placeholder="已导入SN码列表"></textarea>
                                    <div class="mt-2 text-muted" id="snCount"></div>
                                </div>
                                <div id="snStatus" class="mt-2" style="min-height: 50px;"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 网元匹配模块 -->
                <div class="card mb-4 border-primary">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-network-wired me-2"></i>网元匹配</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="csv_file" class="form-label">上传网元信息CSV文件</label>
                                    <div class="input-group">
                                        <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv">
                                    </div>
                                    <small class="form-text text-muted">CSV文件应包含"资产序列号"、"网元名称"和"单板类型"字段</small>
                                </div>
                                <div class="form-group mb-3">
                                    <button type="button" class="btn btn-primary" id="matchBtn">
                                        <i class="fas fa-search me-2"></i>匹配网元
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="network_element" class="form-label">网元名称</label>
                                    <input type="text" class="form-control" id="network_element" name="network_element" readonly>
                                </div>
                                <div class="form-group mb-3">
                                    <label for="type" class="form-label">设备类型</label>
                                    <input type="text" class="form-control" id="type" name="type" readonly>
                                </div>
                                <div id="matchStatus" class="mt-2"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 制造商和制式选择 -->
                <div class="card mb-4 border-primary">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>设备信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="model" class="form-label">设备型号</label>
                                    <input type="text" class="form-control" id="model" name="model" required>
                                </div>
                                <div class="form-group mb-3">
                                    <label for="manufacturer" class="form-label">制造商</label>
                                    <select class="form-select" id="manufacturer" name="manufacturer" required>
                                        <option value="">请选择制造商</option>
                                        <option value="Huawei">Huawei</option>
                                        <option value="ZTE">ZTE</option>
                                        <option value="FiberHome">FiberHome</option>
                                        <option value="other">其他</option>
                                    </select>
                                </div>
                                <div class="form-group mb-3" id="customManufacturerGroup" style="display: none;">
                                    <label for="custom_manufacturer" class="form-label">自定义制造商</label>
                                    <input type="text" class="form-control" id="custom_manufacturer" name="custom_manufacturer">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="standard" class="form-label">制式</label>
                                    <select class="form-select" id="standard" name="standard" required>
                                        <option value="">请选择制式</option>
                                        <option value="2G">2G</option>
                                        <option value="4G">4G</option>
                                        <option value="5G">5G</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 设备照片上传 -->
                <div class="card mb-4 border-primary">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-camera me-2"></i>设备照片</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="equipment_image" class="form-label">上传设备照片</label>
                                    <div class="input-group">
                                        <input type="file" class="form-control" id="equipment_image" name="equipment_image" accept="image/*">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <img id="imagePreview" class="img-fluid rounded shadow-sm" style="max-height: 200px; display: none;">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="text-center">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-save me-2"></i>保存入库
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 扫描模态框 -->
<div class="modal fade" id="scanModal" tabindex="-1" role="dialog" aria-labelledby="scanModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="scanModalLabel">扫描SN码</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="text-center">
                    <video id="scanner" width="100%" height="auto" style="max-width: 400px;"></video>
                    <div class="mt-3">
                        <input type="file" id="fileInput" accept="image/*" class="d-none">
                        <button type="button" class="btn btn-outline-primary" onclick="document.getElementById('fileInput').click()">
                            <i class="fas fa-upload"></i> 上传图片
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    // 设置当前时间
    var now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.getElementById('date').value = now.toISOString().slice(0,16);

    // 文件输入显示文件名
    $('input[type="file"]').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').html(fileName);
    });

    // 图片预览
    $('#equipment_image').on('change', function() {
        var file = this.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#imagePreview').attr('src', e.target.result).show();
            }
            reader.readAsDataURL(file);
        }
    });

    // 制造商选择处理
    $('#manufacturer').on('change', function() {
        if ($(this).val() === 'other') {
            $('#customManufacturerGroup').show();
            $('#custom_manufacturer').prop('required', true);
        } else {
            $('#customManufacturerGroup').hide();
            $('#custom_manufacturer').prop('required', false);
        }
    });

    // 清除SN码
    $('#clearSn').on('click', function() {
        $('#sn').val('');
        $('#snStatus').html('');
    });

    // SN码识别
    $('#recognize-btn').on('click', function() {
        var formData = new FormData();
        var file = $('#sn_image')[0].files[0];
        
        if (!file) {
            $('#snStatus').html('<div class="alert alert-danger">请先选择SN码图片文件</div>');
            return;
        }
        
        formData.append('sn_image', file);
        
        $.ajax({
            url: '/recognize_sn',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('#recognize-btn').prop('disabled', true);
                $('#snStatus').html('<div class="alert alert-info">正在识别SN码...</div>');
            },
            success: function(response) {
                console.log('Response:', response);
                if (response.success) {
                    $('#sn').val(response.message);
                    $('#snStatus').html('<div class="alert alert-success">SN码识别成功：' + response.message + '</div>');
                    // 清空网元匹配相关字段
                    $('#network_element').val('');
                    $('#type').val('');
                    $('#model').val('');
                    $('#matchStatus').html('');
                } else {
                    var errorMessage = response.message || '识别失败，请重试';
                    $('#snStatus').html('<div class="alert alert-danger">' + errorMessage + '</div>');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                console.error('Status:', status);
                console.error('Response:', xhr.responseText);
                var errorMessage = '识别失败，请重试';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                $('#snStatus').html('<div class="alert alert-danger">' + errorMessage + '</div>');
            },
            complete: function() {
                $('#recognize-btn').prop('disabled', false);
            }
        });
    });

    // 当SN码输入框值改变时，清空网元匹配相关字段
    $('#sn').on('input', function() {
        $('#network_element').val('');
        $('#type').val('');
        $('#model').val('');
        $('#matchStatus').html('');
    });

    // 批量导入SN码
    $('#importSnTxt').on('click', function() {
        const fileInput = document.getElementById('sn_txt_file');
        const file = fileInput.files[0];
        if (!file) {
            alert('请先选择txt文件');
            return;
        }
        const reader = new FileReader();
        reader.onload = function(e) {
            const content = e.target.result;
            // 按行分割，去除空行和首尾空格
            const snList = content.split(/\r?\n/).map(s => s.trim()).filter(s => s);
            $('#snListArea').val(snList.join('\n'));
            $('#snCount').text('已导入 ' + snList.length + ' 条SN码');
        };
        reader.readAsText(file, 'utf-8');
    });

    // 点击SN码列表中的某一行，填入输入框
    $('#snListArea').on('click', function(e) {
        const lines = $(this).val().split(/\r?\n/);
        const pos = this.selectionStart;
        let start = 0;
        for (let i = 0; i < lines.length; i++) {
            if (pos <= start + lines[i].length) {
                $('#sn').val(lines[i]);
                $('#sn').trigger('input');
                break;
            }
            start += lines[i].length + 1;
        }
    });

    // 网元匹配逻辑调整：允许无图片时匹配
    $('#matchBtn').off('click').on('click', function() {
        var formData = new FormData();
        var sn = $('#sn').val().trim();
        var file = $('#csv_file')[0].files[0];
        if (!sn) {
            $('#matchStatus').html('<div class="alert alert-danger">请先输入SN码</div>');
            return;
        }
        if (!file) {
            $('#matchStatus').html('<div class="alert alert-danger">请先上传CSV文件</div>');
            return;
        }
        formData.append('sn', sn);
        formData.append('csv_file', file);
        $.ajax({
            url: '/match_network_element',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('#matchBtn').prop('disabled', true);
                $('#matchStatus').html('<div class="alert alert-info">正在匹配网元信息...</div>');
            },
            success: function(response) {
                if (response.success) {
                    $('#network_element').val(response.network_element);
                    $('#type').val(response.device_type);
                    $('#model').val(response.board_name);
                    $('#matchStatus').html('<div class="alert alert-success">' + response.message + '</div>');
                } else {
                    $('#matchStatus').html('<div class="alert alert-danger">' + response.message + '</div>');
                }
            },
            error: function(xhr) {
                var error = xhr.responseJSON || { message: '匹配失败，请重试' };
                $('#matchStatus').html('<div class="alert alert-danger">' + error.message + '</div>');
            },
            complete: function() {
                $('#matchBtn').prop('disabled', false);
            }
        });
    });

    // 表单提交前验证
    $('#inboundForm').on('submit', function(e) {
        if (!$('#sn').val()) {
            e.preventDefault();
            $('#snStatus').html('<div class="alert alert-danger">请先识别SN码</div>');
            return false;
        }
        
        if ($('#manufacturer').val() === 'other' && !$('#custom_manufacturer').val()) {
            e.preventDefault();
            $('#snStatus').html('<div class="alert alert-danger">请填写自定义制造商</div>');
            return false;
        }
    });
});

let scanner = null;

document.getElementById('scanButton').addEventListener('click', function() {
    $('#scanModal').modal('show');
    startScanner();
});

document.getElementById('fileInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const formData = new FormData();
        formData.append('file', file);

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('sn').value = data.sn_code;
                $('#scanModal').modal('hide');
                stopScanner();
            } else {
                alert(data.error || '识别失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('上传失败');
        });
    }
});

function startScanner() {
    if (scanner) {
        scanner.start();
        return;
    }

    scanner = new Html5Qrcode("scanner");
    scanner.start(
        { facingMode: "environment" },
        {
            fps: 10,
            qrbox: { width: 250, height: 250 }
        },
        onScanSuccess,
        onScanFailure
    );
}

function stopScanner() {
    if (scanner) {
        scanner.stop();
    }
}

function onScanSuccess(decodedText, decodedResult) {
    // 验证SN码格式
    if (/^\d{13}$/.test(decodedText) || /^[A-Za-z0-9]{10,}$/.test(decodedText)) {
        document.getElementById('sn').value = decodedText;
        $('#scanModal').modal('hide');
        stopScanner();
    } else {
        alert('无效的SN码格式');
    }
}

function onScanFailure(error) {
    // 处理扫描失败
    console.warn(`扫描失败: ${error}`);
}

$('#scanModal').on('hidden.bs.modal', function () {
    stopScanner();
});
</script>
{% endblock %}